package com.interview.javabasic;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/*
@李子宁
Happy,happy everyday!
冲鸭！
2021/3/22

*/
public class HMAC_SHA256 {

    public static void main(String[] args) throws UnsupportedEncodingException, InvalidKeyException, NoSuchAlgorithmException {
        String data = "0272a702f5733cb9b50bcd18a387b464aa0c7328df83208c954f6dbef2c36890";
        String key = "HMAC-SHA256 \n" +
                "1616403319\n" +
                "2021-03-22/industry/yxw_request\n" +
                "2acb5fea731884fef54f8fc16a396f043c4c69756fa4ae539b8377c40849658e";

        System.out.println(hmacsha256X16(data, key, "UTF-8"));
    }
    public static String hmacsha256X16(String data, String key,String encoding) throws UnsupportedEncodingException, InvalidKeyException, NoSuchAlgorithmException {
        byte[] bytes = hmacsha256(data,key,encoding);
        StringBuilder sha256StrBuff = new StringBuilder();
        for (byte item : bytes) {
            sha256StrBuff.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));
        }
        return sha256StrBuff.toString();
    }

    private static byte[] hmacsha256(String data,String key,String encoding) throws UnsupportedEncodingException, InvalidKeyException, NoSuchAlgorithmException {
        return hmacsha256(data.getBytes(encoding),key);
    }

    private static byte[] hmacsha256(byte[] data,String key) throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException {
        Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
        SecretKeySpec secret_key = new SecretKeySpec(key.getBytes("utf-8"), "HmacSHA256");
        sha256_HMAC.init(secret_key);
        return sha256_HMAC.doFinal(data);
    }
}
